import numpy as np
import matplotlib.pyplot as plt
import math
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
import PySimpleGUI as sg
import io


class Rlc():
    def __init__(self):
        sg.theme('BluePurple')
        layout = [
            [sg.Text('品质因素Q:', font="25px"), sg.Input(size=(6, 4), key='Q-input'), sg.Text('谐振频率W0:', font="25px"),
             sg.Input(size=(6, 4), key='W-input')],
            [sg.Image(key='-IMAGE-'), sg.Button(button_text='绘制', size=(10, 2), font="20px", key='-draw-')],
            ]
        self.window = sg.Window('串联谐振曲线绘制', layout, finalize=True)
        self.Q = 0
        self.W0 = 0
        self.update = 0

    def draw_matplot(self):
        plt.close('all')
        x_list = np.linspace(self.W0 / 2, self.W0 * 10, 10000)  # 这个表示在-5到5之间生成1000个x值
        _2PI = 2 * math.pi
        y = [abs(1 / (np.complex(1, self.Q * (((w / _2PI) / self.W0) - (self.W0 / (w / _2PI)))))) for w in
             x_list]
        plt.title("Series resonance curve")
        self.fig = plt.figure(figsize=(5, 4), dpi=100)
        self.fig.add_subplot(111).plot(x_list, y)

        plt.ylabel("N(f)")
        plt.xlabel("f")
        # plt.savefig('RLC.jpg')
        # plt.show()  #绘制图像

    def draw_figure(self, element, figure):
        plt.close('all')  # erases previously drawn plots
        canv = FigureCanvasAgg(figure)
        buf = io.BytesIO()
        canv.print_figure(buf, format='png')
        if buf is None:
            return None
        buf.seek(0)
        element.update(data=buf.read())
        return canv

    def run(self):
        # 接收新信息
        self.Q = int(self.values['Q-input'])
        self.W0 = int(self.values['W-input'])
        # 准备曲线信息
        self.draw_matplot()
        # 画图
        self.draw_figure(self.window['-IMAGE-'],self.fig)

    def circle_event(self):
        while True:
            event, self.values = self.window.read()
            if event == '-draw-':
                if not (self.values['Q-input'].isdigit() and self.values['W-input'].isdigit()):
                    sg.popup_quick_message('Q和W0需输入数字！！！')
                    pass
                else:
                    self.update = 1
                    # 绘制图片
                    self.run()

            if event in (sg.WIN_CLOSED, 'Exit'):
                break
            self.window['-draw-'].update(
                '更新曲线' if self.update else '绘制')

        self.window.close()


if __name__ == '__main__':
    rcl = Rlc()
    rcl.circle_event()
